package com.cxx.home.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cxx.framework.web.CustomException;
import com.cxx.home.dao.ProductDao;
import com.cxx.home.dto.product.ProductDto;
import com.cxx.home.entity.*;
import com.cxx.home.mapper.*;
import com.cxx.home.service.ProductService;
import com.cxx.home.vo.ProductQueryVo;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ProductServiceImpl implements ProductService {
    @Resource
    private ProductDao productDao;

    @Resource
    private ProductMapper productMapper;

    @Override
    @Transactional
    public Boolean addProduct(ProductDto productDto) {
        LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
        if (productMapper.exists(queryWrapper.eq(Product::getName, productDto.getName()))) {
            throw new CustomException("该商品已经存在");
        }

        Product product = new Product();
        BeanUtils.copyProperties(productDto, product);
        return productMapper.insert(product) == 1;
    }

    @Override
    @Transactional
    public Boolean updateProduct(Long id, ProductDto productDto) {
        if (productMapper.selectById(id) == null) {
            throw new CustomException("该商品不存在");
        }

        Product product = new Product();
        BeanUtils.copyProperties(productDto, product);
        product.setId(id);
        return productMapper.updateById(product) == 1;
    }

    @Override
    @Transactional
    public Boolean deleteProduct(Long id) {
        return productMapper.deleteById(id) == 1;
    }

    @Override
    public ProductDto queryProduct(Long id) {
        if (productMapper.selectById(id) == null) {
            throw new CustomException("该商品不存在");
        }

        return productDao.queryProduct(id);
    }

    @Override
    public List<ProductDto> queryProductList(ProductQueryVo queryVo) {
        return productDao.queryProductList(queryVo);
    }

    @Override
    public List<String> queryProductCategory() {
        return productDao.queryProductCategory();
    }
}
